package org.mms.service.impl;

import org.mms.exception.BusinessException;
import org.mms.pojo.dto.DepartmentDto;
import org.mms.pojo.entity.Department;
import org.mms.pojo.request.DepartmentRequest;
import org.mms.repository.DepartmentRepository;
import org.mms.service.DepartmentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public List<DepartmentDto> list() {
        return departmentRepository.findAll().stream().map(entity -> {
            DepartmentDto dto = new DepartmentDto();
            BeanUtils.copyProperties(entity, dto);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public DepartmentDto getById(Long id) {
        Department entity = departmentRepository.findById(id)
                .orElseThrow(() -> new BusinessException("部门不存在"));
        DepartmentDto dto = new DepartmentDto();
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }

    @Override
    public void create(DepartmentRequest request) {
        Department entity = new Department();
        BeanUtils.copyProperties(request, entity);
        departmentRepository.save(entity);
    }

    @Override
    public void update(DepartmentRequest request) {
        Department entity = departmentRepository.findById(request.getId())
                .orElseThrow(() -> new BusinessException("部门不存在"));
        BeanUtils.copyProperties(request, entity);
        departmentRepository.save(entity);
    }

    @Override
    public void delete(Long id) {
        departmentRepository.deleteById(id);
    }
}